<template>
	<div id="index">
		<!-- 弹窗进度条 -->
		<div style="display:none;" id="download-progress-container">
			<div class="layui-progress layui-progress-big" lay-filter="download-progress" lay-showPercent="true">
				<div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>
			</div>
		</div>

		<!-- 设置界面 -->
		<div class="layui-layout layui-layout-admin setting_layout" v-show="!index_active">
			<setting @backIndex="goIndex" @refresh_application_categories="refresh_application_categories"></setting>
		</div>

		<!-- 主界面 -->
		<div class="layui-layout layui-layout-admin main_layout" v-show="index_active">

			<div class="layui-header header layui-bg-blue" :class="{'head-hidden':headState}">
				<div class="container_row_c_s">

					<div v-if="isUrlMode" class="search_container container_row_c_b is-url-mode">
						<input @keyup.enter="gotoUrl" v-model.trim="urlPath" type="text" placeholder="请输入网址"
							autocomplete="off" class="layui-input">
						<i @click="gotoUrl" class="search_btn layui-icon layui-icon-search"></i>
					</div>

					<div v-else class="search_container container_row_c_b">
						<input @keyup.enter="searchBtnClick" v-model.trim="searchWord" type="text" placeholder="请输入搜索词"
							autocomplete="off" class="layui-input">
						<i @click="searchBtnClick" class="search_btn layui-icon layui-icon-search"></i>
					</div>


					<!-- 设置类别列表 -->
					<ul class="layui-nav layui-bg-blue main_nav">

						<template v-for="category in categories">
							<li :class="{'layui-this':category.isShow}" class="layui-nav-item"
								@click="switchCategory(category)">
								<a href="#">{{category.name}}</a>
							</li>
						</template>

					</ul>

					<!-- 设置功能菜单 -->
					<ul class="layui-nav layui-layout-right main_nav">
						<li class="layui-nav-item">
							<i @click="switchMenuState" v-if="!menuState" title="[关闭/打开]菜单"
								class="layui-icon">&#xe668</i>
							<i @click="switchMenuState" v-else title="[关闭/打开]菜单" class="layui-icon">&#xe66b</i>
						</li>

						<li class="layui-nav-item">
							<i @click="switchFullScreen(true)" title="[启动/关闭]全屏" class="layui-icon">&#xe622</i>
						</li>

						// 跳转到设置界面
						<li class="layui-nav-item">
							<i title="设置" class="layui-icon" @click="goSetting">&#xe714;</i>
						</li>
					</ul>
				</div>
			</div>

			<div class="layui-side layui-bg-gray" :class="{'side-close':menuState}">
				<div class="layui-side-scroll">
					<ul class="search_list" lay-filter="test">
						<li class="search_item" :class="{'active':item.display}" @click.ctrl="openUrlOnWin(item)"
							@click.alt="reloadItem(item)" v-for="item in items" :data-id="item.id"
							@click="searchItemClick(item)">
							<div class="container_row_c_s">
								<img :src="item.favicon" class="item_icon" onerror="src='./static/icon.ico'">
								<p class="item_title" :title="item.desc" v-text="item.name"></p>
							</div>
						</li>
					</ul>
				</div>
			</div>

			<div class="layui-body"
				:class="{'side-close':menuState,'side-not-close':!menuState,'head-hidden':headState,'head-not-hidden':!headState}">
				<div ref="lottie" v-show="isShowLoadIframe" class="lottie"></div>
				<!-- 内容主体区域 -->
				<webview v-for="iframeInfo in iframeInfoList" :key="iframeInfo.id" :ref="iframeInfo.id"
					class="iframe_body" :style="{'z-index' :(iframeInfo.display ? 5 : 1 )}"
					v-show="(iframeInfo.parentId == currentCategory.id) && (!menuState || iframeInfo.display)"
					:src="searchState?iframeInfo.searchUrl:iframeInfo.url" width="100%" :preload="iframeInfo.preload"
					height="100%" plugins></webview>
			</div>

		</div>
	</div>
</template>

<script>
	import lottie from 'lottie-web';
	import {
		ipcRenderer,
		shell
	} from 'electron';
	import urlUtil from 'url';

	ipcRenderer.on("message", (event, text) => {
		console.log(event, text);
	});

	ipcRenderer.on("updateAva", (event, info) => {
		console.log("info", info);
		var isUpdateWin = window.layer.confirm(info.msg, {
			title: "有新的版本可更新",
			icon: 1,
			move: false,
			btn: ['自动更新', '手动更新']
		}, function() {

			window.layer.close(isUpdateWin);
			window.layer.open({
				type: 1,
				title: "更新进度",
				move: false,
				closeBtn: 0,
				area: ['600px', '100px'],
				fixed: true, //不固定
				content: layui.$('#download-progress-container')
			})

			ipcRenderer.send("downloadUpdate");

		}, function() {
			shell.openExternal(info.url);
		});
	});

	//注意：“downloadProgress”事件可能存在无法触发的问题，只需要限制一下下载网速就好了
	ipcRenderer.on("downloadProgress", (event, progressObj) => {
		console.log("当前下载进度为：", progressObj);
		var percent = Math.round(parseFloat(progressObj.percent));
		window.element.progress('download-progress', percent + '%');
	});


	function createSearchUrl(item, word, win) {
		var url = item.url;
		if (item.createSearchUrlJs) {
			var createSearchUrlJs = item.createSearchUrlJs
				.replace(/\$\{url\}/g, "'" + url + "'")
				.replace(/\$\{word\}/g, "'" + word + "'")
			win.executeJavaScript(createSearchUrlJs);
			return undefined;
		}
		return eval(item.createSearchUrl);
	}



	import Setting from './Setting'
	import default_categories from '@/plugin/application-categories'

	export default {
		name: 'index',
		components: {
			Setting
		},
		data: () => {
			return {
				categories: [],
				items: [],
				currentItem: undefined,
				currentCategory: undefined,
				iframeInfoList: [],

				// 搜索词
				searchWord: "",
				urlPath: "",
				isUrlMode: false,
				searchState: false,
				isShowLoadIframe: false,
				menuState: false,
				headState: false,
				fullScreenState: false,

				// 默认显示主页
				index_active: true,
				// 当前id下标
				currentIdx: 1,
			}
		},
		methods: {

			/* 初始化category 设置id*/
			setId: function(categories) {
				// 通过这样递增的方式让id不重复
				var idx = this.currentIdx;

				for (var i = 0; i < categories.length; i++) {
					var category = categories[i];
					category.id = idx++;

					var items = category.items;
					if (items && items.length > 0) {
						for (var j = 0; j < items.length; j++) {
							var item = items[j];
							item.parentId = category.id;
							item.id = idx++;
						}
					}
				}

				this.currentIdx = idx;
			},

			gotoUrl: function(event) {
				try {
					urlUtil.parse(this.urlPath);
				} catch (e) {
					window.layer.msg("网址格式有误", {
						icon: 5
					})
					return;
				}
				this.$refs[this.currentItem.id][0].src = this.urlPath;
			},

			// 刷新item
			reloadItem: function(item) {
				this.isShowLoadIframe = true;
				this.$ref[item.id].reload();
			},

			// 菜单切换事件
			switchMenuState: function(event) {
				this.menuState = !this.menuState;
			},

			// 全屏事件
			switchFullScreen: function(flag) {
				if (!this.menuState && flag) {
					this.menuState = true;
				}
				this.headState = flag;
			},

			// 进到设置页面
			goSetting: function() {
				this.index_active = false;
			},

			// 进到主页面
			goIndex: function() {
				this.index_active = true;
			},

			// 点击搜索按钮
			searchBtnClick: function(event) {
				if (this.currentItem) {
					if (!this.searchWord) {
						window.layer.msg("要先输入搜索的关键字哦", {
							icon: 5
						})
						return
					}

					this.items.forEach((item) => {
						item.searchUrl =
							createSearchUrl(item, this.searchWord, this.$refs[item.id][0]);
					});

					this.searchState = true;
					this.iframeInfoList.sort((o1, o2) => {
						return o1.id - o2.id;
					});

					this.isShowLoadIframe = true;
					this.items.forEach((item) => {
						if (item.searchUrl) {
							this.$refs[item.id][0].reload();
						}
					});
				}
			},

			// 点击item事件
			searchItemClick: function(item) {

				var currentIsUfd = typeof this.currentItem === "undefined";
				if (currentIsUfd) {
					this.currentItem = item;
				} else if (this.currentItem.id !== item.id) {
					this.currentItem.display = false;
					this.currentItem = item;
				} else {
					return;
				}

				item.display = true;
				this.iframeInfoList.sort((o1, o2) => {
					return o1.id - o2.id;
				});
			},

			// 打开一个URL在win上
			openUrlOnWin: function(item) {
				var currentWin = this.$refs[item.id][0];
				shell.openExternal(currentWin.getURL());
			},

			// 初始化items
			initItems: function(items) {
				// this.iframeInfoList.splice(0);
				this.isShowLoadIframe = true;
				items.forEach((item) => {
					item.display = false;

					this.iframeInfoList.push(item);
					this.watchWindow(item);
				})
			},

			destroyItems: function(items) {

			},

			// 切换分类
			switchCategory: function(category) {
				if (category.isShow) {
					return
				}

				// 设置之前选择类别展示属性为false
				if (typeof this.currentCategory !== 'undefined') {
					this.currentCategory.isShow = false;
				}

				// 设置当前类别显示属性为true
				category.isShow = true;
				this.currentCategory = category;

				// 切换新分类下的items
				this.items = this.filter(this.currentCategory.items);

				if (!category.isInitItems) {
					category.isInitItems = true;
					this.initItems(category.items);
				}

				this.searchState = false;


				if (this.items.length > 0) {
					this.searchItemClick(this.items[0]);
				}

				this.categories.sort((o1, o2) => {
					return o1.id - o2.id;
				});
			},

			// 过滤掉设置del为true的item
			filter: function(items) {
				var tmpItems = [];
				items.forEach((item) => {
					// item被删除，则不管
					if (item.del && item.del === true) {
						return;
					}

					tmpItems.push(item);
				});
				return tmpItems;
			},
			watchWindow: function(item) {
				setTimeout((id, that) => {
					var tmpWin = that.$refs[id][0];

					// 设置监听器
					tmpWin.addEventListener('dom-ready', () => {

						// 设置css
						if (item.css) {
							tmpWin.insertCSS(item.css);
						}

						// 执行js
						if (item.evalJs) {
							tmpWin.executeJavaScript(item.evalJs);
						}



						if (that.currentItem.id == item.id) {
							that.isShowLoadIframe = false;
						}

						var urlPath = urlUtil.parse(tmpWin.getURL());
						var path = urlPath.host + "-" + urlPath.path;

						// 插入全局css
						var globalItemCss = "";
						if (globalCss && globalCss instanceof Object) {
							for (var key in globalCss) {
								if (new RegExp(key).test(path)) {
									globalItemCss += globalCss[key];
								}
							}
						}

						tmpWin.insertCSS(globalItemCss);

						// 插入全局js
						var globalItemJs = "";
						if (globalJs && globalJs instanceof Object) {
							for (var key in globalJs) {
								if (new RegExp(key).test(path)) {
									globalItemJs += globalJs[key];
								}
							}
						}

						tmpWin.executeJavaScript(globalItemJs);


					});

					tmpWin.addEventListener('new-window', (e) => {
						const protocol = urlUtil.parse(e.url).protocol;
						if (protocol === 'http:' || protocol === 'https:') {
							tmpWin.src = e.url;
						}
					});

				}, 500, item.id, this)
			},
			refresh_application_categories: function() {
				// 让其重新进行刷新
				this.init_application_categories();
			},
			init_application_categories: function() {
				var applicationCategories = localStorage.getItem("applicationCategories");
				if (applicationCategories && applicationCategories.length > 0) {
					applicationCategories = JSON.parse(applicationCategories)
				}

				// 第一次安装设置默认为空
				if (!applicationCategories) {
					// 类别为空则设置为默认值
					applicationCategories = default_categories
				}

				var that = this;
				// 加载sites
				that.categories = applicationCategories;
				that.setId(that.categories);
				if (that.categories.length > 0) {
					that.switchCategory(that.categories[0]);
				}
			}
		},
		watch: {
			searchWord: function(value) {
				if (value === "") {
					this.searchState = false;
				}
			},
			isShowLoadIframe: function(value) {
				// 加载时间不能超过3s
				if (value) {
					setTimeout(function(app, b) {
						app.isShowLoadIframe = b;
					}, 5000, this, false)
				}
			},
			currentCategory: function() {
				clearTimeout(this.currentCategoryTimeoutIndex)
				this.currentCategoryTimeoutIndex = setTimeout((app) => {
					// 去除不在的分类item
					app.iframeInfoList = app.iframeInfoList.filter(iframeInfo => {
						return app.currentCategory.id == iframeInfo.parentId
					})

					app.categories.forEach(category => {
						if (category.id != app.currentCategory.id) {
							delete category.isInitItems;
						}
					})
				}, 10 * 1000, this)
			}
		},
		mounted: function() {


			// 发送给主进程，让其检查更新
			ipcRenderer.send("checkForUpdate");

			// 初始化网站数据
			this.init_application_categories();

			// 加载动画
			lottie.loadAnimation({
				container: this.$refs.lottie,
				renderer: 'svg',
				loop: true,
				autoplay: true,
				animationData,
			});

			// 设置快捷键
			var that = this;
			ipcRenderer.on("shortcut-func", function(event, arg) {
				var currentWin = that.$refs[that.currentItem.id][0];
				switch (arg) {
					case "CommandOrControl+H":
						currentWin.src = that.currentItem.url;
						break;

					case "CommandOrControl+G":
						that.isUrlMode = !that.isUrlMode
						break;

					case "CommandOrControl+L":
						that.isUrlMode = !that.isUrlMode
						break;

					case "CommandOrControl+Left":
						if (!currentWin.canGoBack()) {
							return;
						}
						currentWin.goBack();
						break;
					case "CommandOrControl+Right":
						if (!currentWin.canGoForward()) {
							return;
						}
						currentWin.goForward();
						break;
					case "CommandOrControl+Up":
						var i = 0;
						for (; i < that.items.length; i++) {
							var item = that.items[i];
							if (item.id === that.currentItem.id) {
								break;
							}
						}
						if (i == 0) {
							return;
						}
						that.searchItemClick(that.items[i - 1]);
						break;
					case "CommandOrControl+Down":
						var i = 0;
						for (; i < that.items.length; i++) {
							var item = that.items[i];
							if (item.id === that.currentItem.id) {
								break;
							}
						}
						if (i == that.items.length - 1) {
							return;
						}
						that.searchItemClick(that.items[i + 1]);
						break;
					case "F5":
						this.isShowLoadIframe = true;
						currentWin.reload();
						break;
					case "CommandOrControl+F12":
						currentWin.openDevTools();
						break;
					case "ESC":
						if (that.headState) {
							that.headState = false;
						}
						break;
				}
			})

			ipcRenderer.on("log", function(event, arg) {
				console.log(arg);
			});

		}
	};
</script>

<style>
	#index,
	#setting {
		height: 100%;
		width: 100%;
	}

	.setting_layout,
	.main_layout {
		height: 100%;
		width: 100%;
	}

	#download-progress-container {
		padding: 20px;
	}
</style>
